<template>
    <div class="cardComputeView" :style="carStyle">
        <div class="lineTitle" :style="titleStyle">{{ obj.title }}</div>
        <div class="gotoViewBtn" v-if="isGotoView" @click="gotoUrl(obj)"></div>

        <button class="btn_dashed" @click="dialogFormVisible = true">查&nbsp;询</button>
        <div class="sppedview">
            <div class="speedcontent" :style="contentStyle" ref="lineContent">
                <template v-for="item in lineData">
                    <div class="line" :style="item.style" v-if="item.isShowTitle"
                        :title="'时间：' + item.date + '\n' + '数据：' + item.value">
                        <!-- <span v-if="item.isShowTime" :style="timeStyle">{{ item.date }}</span> -->
                    </div>
                    <div class="line" :style="item.style" v-else></div>
                </template>
            </div>
            <div class="scaleinfo">
                <span v-for="(item, index) in scaleData" :key="index" :style="item.style">{{ item.date }}</span>
            </div>
            <!-- <span class="speedtime" :style="timeStyle">{{ beginTime }}</span> -->
            <!-- <span class="speedtime sp2" :style="timeStyle">{{ endTime }}</span> -->
        </div>

        <!-- 筛选弹窗 -->
        <el-dialog width="550px" title="查询数据" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
            append-to-body>
            <el-form ref="formRef" class="dialog-from-margin" :rules="rules" status-icon :model="filterFormSet"
                label-position="left" label-width="60px">
                <el-form-item label="范围：" prop="filterTime">
                    <el-date-picker size="small" v-model="filterFormSet.filterTime" type="date" placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="filterData()">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from "moment"
// import { cardDataLoad, boardLoad } from '@/api/share'

export default {
    Name: "TimeSpeed",
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
    },
    data() {
        var checkDatetime = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请选择筛选时间"));
            } else {
                callback();
            }
        };
        return {
            value: 0,
            titleStyle: {},
            timeStyle: {},
            contentStyle: {},
            carStyle: {},
            timer: null,
            beginTime: 0,
            endTime: 0,
            filterForm: {
                pageInfo: {
                    pageSize: 86000,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                endTime: "",
                beginTime: "",
                structureIds: [],
                filterTime: "",
            },
            filterFormSet: {
                filterTime: "",
            },
            columns: [],
            dataList: [],
            lineData: [],
            lineWidth: 0,
            minutes: 0,
            scaleData: [],
            // 筛选弹窗
            rules: { filterTime: [{ validator: checkDatetime, trigger: "blur" }], },
            dialogFormVisible: false,
        }
    },
    mounted() {
        this.setStyle();
        this.dataStr = JSON.stringify(this.obj.tableData);

        var self = this;
        this.$nextTick(() => {
            self.init();

            self.reloadInfo();
        });
    },
    methods: {
        reloadInfo() {
            clearInterval(this.timer)
            this.lineData = [];
            // 第一次获取
            this.getLineData((dataResult) => {
                this.columns = dataResult.columns;
                this.dataList = dataResult.dataList;

                this.datainitializ();

                // 循环刷新
                this.timedRefresh();
            });
        },
        // setLineStyle(item) {
        //     var value = item[0];
        //     var style = {};
        //     this.obj.tableData.status.forEach(e => {
        //         if (value >= e.value1 && value <= e.value2) {
        //             style.backgroundColor = e.color;
        //         }
        //     });
        //     return style;
        // },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";


            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
            }

            this.titleStyle = {
                fontSize: style.fontSize + "px",
                color: style.color,
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
                justifyContent: style.justifyContent,
                alignItems: "flex-start",
            };

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion
            
            // this.timeStyle = {
            //     color: this.obj.tableData.dateTimeColor,
            //     fontSize: this.obj.tableData.dateTimeSize + "px",
            //     fontStyle: this.obj.tableData.dateTimeStyle,
            //     fontWeight: this.obj.tableData.dateTimeWeight,
            // }

            this.contentStyle = {
                backgroundColor: this.obj.tableData.endColor
            }
        },
        // 初始化和样式绘制
        init() {
            // 日期筛选
            if (this.filterForm.filterTime) {
                var startTime = moment(this.filterForm.filterTime).format("YYYY/MM/DD H:mm");
                var endTime = moment(this.filterForm.filterTime).format("YYYY/MM/DD ") + "23:59:59";
            } else {
                var startTime = moment().format("YYYY/MM/DD ") + this.obj.tableData.startTime + ":00";
                if (this.obj.tableData.endTime == '24:00') {
                    var endTime = moment().format("YYYY/MM/DD ") + "23:59:59";
                    this.endTime = "24:00";
                } else {
                    var endTime = moment().format("YYYY/MM/DD ") + this.obj.tableData.endTime + ":00";
                    this.endTime = moment(endTime).format("H:mm");
                }
            }
            this.beginTime = moment(startTime).format("H:mm");

            var contentWidth = this.$refs.lineContent.offsetWidth;

            var minutes = Number((new Date(endTime) - new Date(startTime)) / 1000 / 60).toFixed(0);
            this.minutes = minutes; // 总分钟数
            this.lineWidth = Number(contentWidth / minutes).toFixed(2);
            // alert(this.lineWidth);
            this.filterForm.beginTime = startTime;
            this.filterForm.endTime = endTime;

            // 计算刻度和对应日期
            var hourLength = Number((new Date(endTime) - new Date(startTime)) / 1000 / 60 / 60).toFixed(0);
            if (hourLength > 2) {
                var scale = Math.floor(hourLength / 2);
                var data = [];
                var style = {
                    width: Number(contentWidth / scale).toFixed(2) + 'px',
                    color: this.obj.tableData.dateTimeColor,
                    fontSize: this.obj.tableData.dateTimeSize + "px",
                    fontStyle: this.obj.tableData.dateTimeStyle,
                    fontWeight: this.obj.tableData.dateTimeWeight,
                }
                var dateTime = new Date(startTime);
                for (var i = 0; i <= scale; i++) {
                    if (i > 0) {
                        dateTime = moment(dateTime).add(2, 'hour');
                    }
                    if (i == scale) {
                        dateTime = new Date(endTime);
                    }
                    data.push({
                        date: moment(dateTime).format("H:mm"),
                        style
                    })
                }
                this.scaleData = data;
            }
        },
        // 定时刷新
        timedRefresh() {
            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            if (this.isReload) {
                this.timer = setInterval(() => {
                    // var start = new Date();
                    // const end = new Date();
                    // if (this.dataList.length) {
                    //     // 使用返回的记录列表最新的x轴当做开始时间 如果第一条记录不为时间不做刷新处理
                    //     start = new Date(this.dataList[this.dataList.length - 1][0]);
                    //     start.setTime(start.getTime() + 1000);
                    // } else {
                    //     start.setTime(start.getTime() - timeSize * 1000);
                    // }
                    // this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d} {h}:{i}:{s}");
                    // this.filterForm.endTime = this.parseTime(end, "{y}-{m}-{d} {h}:{i}:{s}");
                    this.getLineData((dataResult) => {
                        if (dataResult.dataList) {
                            this.columns = dataResult.columns;
                            this.dataList = dataResult.dataList;

                            this.datainitializ();
                        }
                    });
                }, timeSize * 1000);
            }
        },
        getLineData(callback) {
            if (this.obj.tableData.tableId && this.obj.tableData.dateId && this.obj.tableData.valueId) {
                this.showContent = true;

                this.filterForm.tableId = this.obj.tableData.tableId;
                this.filterForm.structureIds = [this.obj.tableData.dateId, this.obj.tableData.valueId];
                if (this.obj.tableData.type != 1) {
                    cardDataLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            if (callback) {
                                callback(res.data.data.dataResult);
                            }
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                } else {
                    boardLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            if (callback) {
                                callback(res.data.data.dataResult);
                            }
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                }
            }
        },
        datainitializ() {
            var newData = [];

            if (this.dataList && this.dataList.length) {
                var timeindex = 0;
                var valueindex = 1;
                if (this.columns[0].id == this.obj.tableData.valueId) {
                    var timeindex = 1;
                    var valueindex = 0;
                }
                var endTime = this.dataList[0][timeindex];
                this.dataList.reverse();
                // 计算空档期
                var beginTime = this.dataList[0][timeindex];
                beginTime = beginTime.replace(/\-/g, '/');

                if (this.filterForm.filterTime) {
                    var startTime = moment(this.filterForm.filterTime).format("YYYY/MM/DD H:mm");
                } else {
                    var startTime = moment().format("YYYY/MM/DD ") + this.obj.tableData.startTime + ":00";
                }

                var startMinutes = Number((new Date(beginTime) - new Date(startTime)) / 1000 / 60);
                // alert(startMinutes)
                // newData.length = startMinutes;
                var nullcolor = this.obj.tableData.endColor;
                for (var i = 0; i < startMinutes; i++) {
                    var data = {
                        date: "",
                        isShowTime: false,
                        isShowTitle: false,
                        style: {
                            width: this.lineWidth + "px",
                            backgroundColor: nullcolor,
                        }
                    };
                    newData.push(data);
                }
                // alert(beginTime + "--" + startTime)
                var parentDate = new Date(startTime);
                var parentTime = moment(parentDate).format("HH:mm");
                this.dataList.forEach((e, index) => {
                    var time = moment(e[timeindex]).format('HH:mm')
                    var value = e[valueindex];
                    var data = {
                        date: time,
                        isShowTime: false,
                        value,
                        isShowTitle: true,
                        style: {
                            width: this.lineWidth + "px",
                            backgroundColor: nullcolor,
                            cursor: 'pointer'
                        }
                    };
                    // 判断分钟是否重复
                    if (time != parentTime) {
                        // 判断时间是否是下一分钟
                        var dq = moment(parentDate).add(1, 'minute');
                        var curentTime = new Date(e[timeindex]);
                        var forsize = Number((curentTime - dq) / 1000 / 60).toFixed(0);
                        // 相差分钟数 插入空白位置
                        if (index > 0 && forsize > 0) {
                            // var parentdata = newData[newData.length - 1];
                            // console.log(parentdata);
                            var parentdata = {
                                date: '',
                                isShowTime: false,
                                value,
                                isShowTitle: false,
                                style: {
                                    width: this.lineWidth + "px",
                                    backgroundColor: nullcolor,
                                    cursor: ''
                                }
                            };
                            if (forsize == 1) {
                                newData.push(parentdata);
                            } else {
                                for (var j = 0; j < forsize; j++) {
                                    newData.push(parentdata);
                                }
                            }
                        }
                        this.obj.tableData.status.forEach(state => {
                            if (value * 1 >= state.value1 && value * 1 <= state.value2) {
                                data.style.backgroundColor = state.color;
                            }
                        });
                        // if (parentColor != "" && parentColor != nullcolor && data.style.backgroundColor != parentColor) {
                        //     data.isShowTime = true;
                        // }
                        newData.push(data);
                        // parentColor = data.style.backgroundColor;
                        parentTime = time;
                        parentDate = new Date(e[timeindex]);
                    }
                })
            }

            var endInfo = newData[newData.length - 1];
            var endTime = this.obj.tableData.endTime;
            if (this.obj.tableData.endTime == '24:00') {
                endTime = "23:59";
            }
            if (endInfo.time != endTime) {
                endInfo.isShowTime = true;
            }

            this.lineData = newData;
        },
        filterData() {
            this.$refs["formRef"].validate((valid) => {
                if (valid) {
                    this.filterForm.filterTime = this.filterFormSet.filterTime;
                    this.dialogFormVisible = false;
                    this.init()

                    clearInterval(this.timer);
                    this.lineData = [];
                    this.getLineData((dataResult) => {
                        this.columns = dataResult.columns;
                        this.dataList = dataResult.dataList;

                        this.datainitializ();
                    });
                }
            });
        },
    },
    watch: {
        obj: {
            deep: true,  // 深度监听
            handler(newVal, oldVal) {
                this.setStyle();

                if (this.isEdit && JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);
                    this.init();
                    this.reloadInfo();
                    // this.obj.isClose = false;
                }
            }
        }
    },
    computed: {
        isGotoView() {
            if (this.isEdit == false && this.obj.contactType > 0) {
                if (this.obj.contactType == 1 && this.obj.boardId) {
                    return true;
                }
                if (this.obj.contactType == 2 && this.obj.url) {
                    return true;
                }
            }
            return false;
        }
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}
</script>

<style scoped>
.sppedview {
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    margin: 0 20px;
}

.speedcontent {
    height: 20px;
    width: 100%;
    background: #eeeeee;
    overflow: hidden;
}

.speedtime {
    position: absolute;
    margin-top: 10px;
    left: 0;
    transform: translateX(-30%);
}

.speedtime.sp2 {
    transform: translateX(30%);
    left: initial;
    right: 0;
}

.line {
    height: 100%;
    /* background: #ff0000; */
    width: 0.1px;
    display: inline-block;
}

.line span {
    transform: translate(-18px, 26px);
    position: absolute;
}

.scaleinfo {
    width: 130%;
    margin-top: 12px;
    font-size: 0;
}

.scaleinfo span {
    display: inline-block;
    padding-top: 5px;
    text-indent: -15px;
    position: relative;
    border-top: solid 1px #000;
}

.scaleinfo span::before {
    position: absolute;
    content: "";
    height: 2px;
    width: 1px;
    top: 0;
    left: 0;
}

.scaleinfo span:nth-last-child(1) {
    border-top: none;
}

.scaleinfo span:nth-last-child(1)::before {
    left: -1px;
}

.month-white .scaleinfo span {
    border-color: #333333;
}

.month-white .scaleinfo span::before {
    background: #333333;
}

.dard-black .scaleinfo span {
    border-color: #ffffff;
}

.dard-black .scaleinfo span::before {
    background: #ffffff;
}
</style>